package com.zzyq.pc.web.configure.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.enums.RoleEnum;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.common.plugin.shiro.TokenManager;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.web.configure.model.Depart;
import com.zzyq.pc.web.configure.service.ICompanyService;
import com.zzyq.pc.web.configure.service.IDepartService;
import com.zzyq.pc.web.user.model.Permission;
import com.zzyq.pc.web.user.model.Role;
import com.zzyq.pc.web.user.model.User;
import com.zzyq.pc.web.user.service.IUserService;

@Controller
@RequestMapping(value = "/depart/", produces = "application/json;charset=UTF-8")
public class DepartController extends BaseController {
    @Autowired
    IDepartService departService;
    @Autowired
    ICompanyService companyService;
    @Autowired
    IUserService userService;

    /**
     * 根据参数查询部门列表
     * 
     * @param depart
     *            部门信息
     */
    @ResponseBody
    @RequestMapping("query")
    public String query(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, Depart depart) {
        List<Depart> list = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
        PageView pageView = null;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            // 字符转换
            if (depart == null) {
                depart = new Depart();
            }
            depart.setDepartName(transString(httpRequest, depart.getDepartName()));
            // 这里只能查自己团体下的部门信息
            depart.setCompanyId(TokenManager.getUser().getCompany().getCompanyId());
            // 开始根据参数查询
            list = departService.selectList(pageView, depart);
            // 加入页码和总数
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, list);
        } catch (Exception e) {
            LoggerUtils.fmtError(getClass(), "查询列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, list);
        }
    }

    /**
     * 新增部门信息
     */
    @ResponseBody
    @RequestMapping("add")
    public String add(HttpServletRequest httpRequest, HttpServletResponse response, Depart depart) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            // 检查参数是否有误
            if (depart == null || StringUtils.isBlank(depart.getDepartName())) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 字符转换
            depart.setDepartName(transString(httpRequest, depart.getDepartName()));
            depart.setCompanyId(TokenManager.getUser().getCompany().getCompanyId());
            // 检查是否已存在相同名称的部门
            List<Depart> sames = departService.selectSameList(depart);
            if (sames != null && !sames.isEmpty()) {
                return HttpUtils.formatData(format, CODE_ERROR_SAME, MSG_ERROR_SAME, null);
            }
            // 添加团体信息
            boolean success = departService.add(depart);
            if (success) {
                return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "添加部门信息异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
        return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
    }

    /**
     * 修改部门信息
     */
    @ResponseBody
    @RequestMapping("update")
    public String update(HttpServletRequest httpRequest, HttpServletResponse response, Depart depart) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            // 检查参数是否有误
            if (depart == null || StringUtils.isBlank(depart.getDepartName()) || depart.getDepartId() == null) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 字符转换
            depart.setDepartName(transString(httpRequest, depart.getDepartName()));
            depart.setCompanyId(TokenManager.getUser().getCompany().getCompanyId());
            // 检查是否已存在相同名称的部门
            List<Depart> sames = departService.selectSameList(depart);
            if (sames != null && !sames.isEmpty()) {
                return HttpUtils.formatData(format, CODE_ERROR_SAME, MSG_ERROR_SAME, null);
            }
            // 修改部门信息
            boolean success = departService.update(depart);
            if (success) {
                return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "修改部门信息异常：%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
        return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
    }

    /**
     * 根据ID删除部门信息
     */
    @ResponseBody
    @RequestMapping("delete")
    public String delete(HttpServletRequest httpRequest, HttpServletResponse response, Integer departId) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            // 检查参数是否有误
            if (departId == null) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 查询该部门下是否存在用户，存在用户则不予删除
            List<User> users = userService.selectByDepartId(departId);
            if (!(users == null || users.isEmpty())) {
                return HttpUtils.formatData(format, CODE_ERROR_OTHER, "删除失败，请先清空该部门下的用户", null);
            }
            // 删除部门信息
            boolean success = departService.delete(departId);
            if (success) {
                return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
            }
        } catch (Exception e) {
            LoggerUtils.fmtError(getClass(), "删除部门信息异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
        return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
    }

    /**
     * 查询部门下的用户列表
     */
    @ResponseBody
    @RequestMapping("queryUsers")
    public String queryUsers(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, User user, Integer departId) {
        List<User> users = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, users);
        PageView pageView = null;
        user = user == null ? new User() : user;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            // 取出最大权限级别分数
            // 用户只能查询比自己权限小的用户
            User activeUser = TokenManager.getUser();
            // 判断departId是否有效
            Depart qDepart = new Depart();
            qDepart.setCompanyId(activeUser.getCompany().getCompanyId());
            List<Depart> departs = departService.selectList(null, qDepart);
            boolean flag = false;
            for (Depart depart : departs) {
                if (departId != null && (departId == -1 || departId.intValue() == depart.getDepartId().intValue())) {
                    flag = true;
                    break;
                }
            }
            // 无效的departId,赋值null
            if (!flag) {
                departId = null;
            }
            User qUser = new User();
            qUser.getDepart().setDepartId(departId);
            qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            qUser.setUserAccount(user.getUserAccount());
            qUser.setUserPhone(user.getUserPhone());
            qUser.setUserName(transString(httpRequest, user.getUserName()));
            users = userService.selectAsList(pageView, qUser);
            // 加入页码和总数
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, users);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询用户列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, users);
        }
    }
}
